const TAG = '[CheckLogin]';
const log = (...args: any[]) => console.log(TAG, ...args);

type JarvisModName = 'portal' | 'ds' | 'task' | 'message';

/**
 * 解析出路径中的模块名
 */
const getJarvisModName = (pathname: string): JarvisModName => {
  const modName = (pathname.split('/')[1] || 'portal') as JarvisModName;
  // 未拆分出来的模块, 统一用portal
  return ['authmanage'].includes(modName) ? 'portal' : modName;
};

const checkLoginAndRedirect = (): Promise<string | null> =>
  new Promise((resolve) => {
    const modName = getJarvisModName(location.pathname);
    const ajax = new XMLHttpRequest();
    ajax.open('get', `/${modName}/jarvis/user/permission/profile`);
    ajax.setRequestHeader('Accept', 'application/json');
    ajax.onreadystatechange = () => {
      const { readyState, status, responseText } = ajax;
      if (readyState !== 4) return;
      log('statechange, ', { readyState, status, responseText });

      if (readyState === 4 && status === 200) {
        log('request success!');
        return resolve(ajax.responseText);
      }
      if (status === 401 || status === 500 || status === 0) {
        const currUrl = location.href;

        if (!currUrl.match(/redirectUrl=[^=]+&?/)) {
          const nextUrl = `/${modName}/fjarvisxLogin?redirectUrl=${currUrl}`;
          log('check failed, and url not have redirect_url qs, so just redirect => ', nextUrl);
          location.href = nextUrl;
        } else {
          log('check failed, url have redirect_url param, just ignore!');
        }
        return resolve(null);
      }
      if (status === 403) {
        window.location.href = `/${modName}/v2/403`;
      }
      log('check failed');
      resolve(null);
    };
    ajax.send();
  });

(window as any).checkLoginPromise = checkLoginAndRedirect();
export {};
